package com.meichis.yndms.receiver;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
import android.text.TextUtils;

import com.meichis.mcsappframework.utils.SharePreferenceUtil;
import com.meichis.yndms.http.IWebServiceCallback;
import com.meichis.yndms.model.DSPToken;
import com.meichis.yndms.repository.manager.HeartBeatManager;

public class HeartBeatReceiver extends BroadcastReceiver {

    private Context context;

    @Override
    public void onReceive(final Context context, Intent intent) {
        this.context = context;
        String action = intent.getAction();
        if (action.equals("com.meichis.yndms.intent.HEARTBEAT")) {
            String refreshToken = (String) SharePreferenceUtil.getInstance().getCacheValue(SharePreferenceUtil.PREFERENCES_REFRESHAUTHKEY);
            if (!TextUtils.isEmpty(refreshToken)) {
                HeartBeatManager.getInstance().refreshToken(refreshToken, iWebServiceCallback);
            }
        }
    }

    private IWebServiceCallback iWebServiceCallback = new IWebServiceCallback<DSPToken>() {

        @Override
        public void onSucceed(int sequence,DSPToken dspToken, String ReturnInfo, int Return) {
            SharePreferenceUtil.getInstance().setCacheValue(SharePreferenceUtil.PREFERENCES_AUTHKEY, dspToken.getAccess_token(), dspToken.getExpires_in() / 60);
            SharePreferenceUtil.getInstance().setCacheValue(SharePreferenceUtil.PREFERENCES_REFRESHAUTHKEY, dspToken.getRefresh_token(), 30 * 60 * 24);
            AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            PendingIntent heartIntent = PendingIntent.getBroadcast(context, 0, new Intent("com.meichis.yndms.intent.HEARTBEAT"), PendingIntent.FLAG_UPDATE_CURRENT);
//            JSONObject jsonObject = new JSONObject(AESProvider.decrypt(resultPack.getResult()));
//            SharePreferenceUtil.getInstance().setLongValue(SharePreferenceUtil.PREFERENCES_LASTGETMSGTIME, DateUtil.getMillis(DateUtil.parse(jsonObject.getString("Now"))));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                manager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + dspToken.getExpires_in() * 1000 / 2, heartIntent);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                manager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + dspToken.getExpires_in() * 1000 / 2, heartIntent);
            } else {
                manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + dspToken.getExpires_in() * 1000 / 2, heartIntent);
            }
        }

        @Override
        public void onFailure(int sequence,int errorcode, String error) {

        }
    };

}
